package com.uni.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.uni.base.RestResponse;
import com.uni.pojo.*;

import com.uni.service.ProductService;
import com.uni.utils.PageUtil;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Author:      Unirithe/Mr.Chao
 * CSDN:        https://blog.csdn.net/Unirithe
 * CreatedTime:  2022/1/31 16:18
 **/
@Controller
public class ProductController {
    @Autowired
    ProductService productService;

    @GetMapping("/index.html")
    public String toIndex(ModelMap modelMap){
        modelMap.addAttribute("type", "product");
        return "index";
    }


    /**
     * 跳转到商品详情
     * @return String
     */
    @GetMapping("/product.html/{id}")
    @RequiresAuthentication
    public String toProductDetail(@PathVariable Long id, ModelMap modelMap){
        // 根据商品ID查询商品信息
        Product product = productService.getProductWithProviderById(id);
        // 查询推荐商品
        List<Product> prodInfo = productService.getProductWithTypeBySome(null);
        modelMap.addAttribute("prodType",new Prodtype(0, "所有商品"));
        modelMap.addAttribute("prodInfo",prodInfo.subList(0, 5));
        modelMap.addAttribute("product",product);
        return "product";
    }

    @PostMapping("/product/query")
    @ResponseBody
    public String queryAllProduct(@RequestBody(required = false) Map<String, String> map){
        int pageNow = map == null ? 1 : Integer.parseInt(map.getOrDefault("pageNow", "1"));
        PageHelper.startPage(pageNow ,10);
        List<Product> products = productService.getProductWithTypeBySome(map);
        List<Prodtype> prodtypes = productService.getAllProdType();
        PageInfo pageInfo = PageUtil.setPageInfo(pageNow, 8, products);
        return RestResponse.ok(new HashMap<String, Object>() {{
            put("prodInfo", products);
            put("prodtypesInfo", prodtypes);
            put("pageInfo", pageInfo);
        }}).toJSONString();
    }
}
